package com.platform.comm.common.batch.listener;


import com.platform.comm.entity.CommBatchInfoEntity;
import com.platform.comm.service.ICommBatchInfoBiz;
import com.platform.comm.common.batch.ComBatchExportContext;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 导出任务监听器
 *
 * @author Tommy
 */

@Log4j2
public class ComExportJobListener extends JobExecutionListenerSupport {
    private ComBatchExportContext context;
    private final ICommBatchInfoBiz dirBatchInfoBiz;

    public ComExportJobListener(ComBatchExportContext context, ICommBatchInfoBiz dirBatchInfoBiz) {
        this.context = context;
        this.dirBatchInfoBiz = dirBatchInfoBiz;
    }

    @Override
    public void beforeJob(JobExecution jobExecution) {
        log.info("任务开始启动...");
        log.info("开始时间: {}", LocalDateTime.now());
        log.info(jobExecution.getJobConfigurationName());

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        String jobStatus =jobExecution.getStatus().name();
        saveBatchInfo(jobStatus);

        if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
            log.info("通用批量导出任务已经完成");
        }
        log.info("结束时间: {}" ,LocalDateTime.now());
    }

    private void saveBatchInfo(String status) {
        CommBatchInfoEntity batchInfoEntity = dirBatchInfoBiz.fetchById(context.getDirBatchInfoEntity().getId());
        batchInfoEntity.setTotalCount(BigDecimal.valueOf(context.getBatchResult().getTotalCount()));
        batchInfoEntity.setJobResult(context.getFilePath());
        batchInfoEntity.setJobStatus(status);
        this.dirBatchInfoBiz.saveEntity(batchInfoEntity);
    }
}
